import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_buisiness_2006a/bean/home_banner_bean_result.dart';
import 'package:flutter_buisiness_2006a/bean/home_hot_goods_bean_result.dart';
import 'package:flutter_buisiness_2006a/bean/home_navigator_bean_result.dart';
import 'package:flutter_buisiness_2006a/bean/home_recommend_bean_result.dart';
import 'package:flutter_buisiness_2006a/service/service_method.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_swiper/flutter_swiper.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

///with 时混入的意思,相当于java中的实现接口
///Automatic 自动的,Keep 保持 Alive 存活
class _HomePageState extends State<HomePage>
    with AutomaticKeepAliveClientMixin {
  @override
  void initState() {
    // var formData = {'category_id': 24, 'currentPage': 1, 'pageSize': 10};
    // request('homeHotGoods', formData).then(
    //     (value) => print(HomeHotGoodsBeanResult.fromJson(value).data!.length));
    _getHotGoods();
    super.initState();
  }

  //用于页面刷新增加的size
  int size = 10;

  //火爆专区所有商品的数据源
  List<HomeHotGoodsBean?>? hotGoodsList = [];

  //火爆专区的标题,可以使用=等号的形式来写返回值,这样就不用写return
  Widget hotTitle = Container(
    margin: const EdgeInsets.only(top: 10),
    padding: const EdgeInsets.all(5),
    alignment: Alignment.centerLeft,
    decoration: const BoxDecoration(
        color: Colors.white,
        border: Border(bottom: BorderSide(width: 1, color: Colors.black12))),
    child: const Text(
      '火爆专区',
      style: TextStyle(color: Colors.pink),
    ),
  );

  //火爆专区的WarpList(瀑布流)
  Widget _hotWrapList() {
    if (hotGoodsList!.isNotEmpty) {
      //通过数据源,生成一个item的列表,通过map进行转换,e代表List中每一个元素(商品的bean类)
      List<Widget> listItemWidget = hotGoodsList!.map((e) {
        return InkWell(
          onTap: () {
            print('点击了火爆专区的单品');
          },
          child: Container(
            width: ScreenUtil().setWidth(372).toDouble(),
            color: Colors.white,
            padding: const EdgeInsets.all(5),
            margin: const EdgeInsets.only(bottom: 3),
            child: Column(
              children: [
                //火爆专区item的图片
                Image.network(
                  e!.goods_default_icon!,
                  width: ScreenUtil().setWidth(375).toDouble(),
                ),
                //item的商品名称
                Text(
                  e.goods_desc!, maxLines: 1,
                  overflow: TextOverflow.ellipsis, //设置超出文字限制时,展示什么样的效果
                  style: TextStyle(
                      color: Colors.pink,
                      fontSize: ScreenUtil().setSp(26).toDouble()),
                ),
                //item的商品价格
                Text('团购价:¥${e.goods_default_price}元'),
                Text(
                  '原价:¥${e.goods_default_price}元',
                  style: const TextStyle(
                      color: Colors.black26,
                      decoration: TextDecoration.lineThrough),
                )
              ],
            ),
          ),
        );
      }).toList(); //到此为止,会生成一个widget的集合,通过数据源的集合转换而来
      return Wrap(
        spacing: 2, //有几列的瀑布流效果
        children: listItemWidget,
      );
    } else {
      return const Center(
        child: Text('加载中...'),
      );
    }
  }

  //火爆专区的组合(包含标题和瀑布流)
  Widget _hotGoods() {
    return Column(
      children: [hotTitle, _hotWrapList()],
    );
  }

  //请求主页火爆专区的方法
  void _getHotGoods() {
    var formData = {'category_id': 24, 'currentPage': 1, 'pageSize': size};
    request('homeHotGoods', formData).then((value) {
      List<HomeHotGoodsBean?> newList =
          HomeHotGoodsBeanResult.fromJson(value).data!;
      setState(() {
        hotGoodsList!.addAll(newList);
        size += 10;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, width: 750, height: 1334); //是Iphone6的尺寸基准,设计图的尺寸
    return Scaffold(
      appBar: AppBar(
        title: const Text('百姓生活+'),
      ),
      body: EasyRefresh(
        onRefresh: () async {},
        onLoad: () async {
          _getHotGoods();
        },
        header: ClassicalHeader(
            bgColor: Colors.white,
            textColor: Colors.pink,
            infoColor: Colors.pink,
            showInfo: true,
            noMoreText: '',
            infoText: '刷新中...',
            refreshReadyText: '下拉刷新',
            refreshedText: '刷新完成',
            refreshingText: '正在刷新',
            refreshText: '下拉刷新'),
        footer: ClassicalFooter(
            bgColor: Colors.white,
            textColor: Colors.pink,
            infoColor: Colors.pink,
            showInfo: true,
            noMoreText: '',
            loadReadyText: '上拉加载',
            loadedText: '加载完成',
            loadingText: '正在加载',
            loadText: '上拉加载'),
        child: ListView(
          children: [
            FutureBuilder(
              future: request('homePageBanner', null),
              builder: (context, value) {
                if (value.hasData) {
                  //当Future中有返回值的时候
                  List<HomeBannerBean?>? homeBannerList =
                      HomeBannerBeanResult.fromJson(value.data).data;
                  //把数据源传递到轮播图控件中
                  return SwiperDiy(swiperDataList: homeBannerList);
                } else {
                  //当Future中没有返回值的时候
                  return const Center(
                    child: Text('加载中...'),
                  );
                }
              },
            ),
            FutureBuilder(
                future: request('homeNavigator', null),
                builder: (context, val) {
                  if (val.hasData) {
                    List<HomeNavigatorBean?>? homeNavigatorList =
                        HomeNavigatorBeanResult.fromJson(val.data).data;
                    return HomeNavigator(navigatorList: homeNavigatorList);
                  } else {
                    return const Center(
                      child: Text('加载中...'),
                    );
                  }
                }),
            FutureBuilder(
                future: request('homeRecommend', null),
                builder: (context, val) {
                  if (val.hasData) {
                    List<HomeRecommendBean?>? homeRecommendList =
                        HomeRecommendBeanResult.fromJson(val.data).data!;
                    return HomeRecommend(recommendList: homeRecommendList);
                  } else {
                    return const Center(
                      child: Text('加载中...'),
                    );
                  }
                }),
            _hotGoods()
          ],
        ),
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}

///轮播图控件
class SwiperDiy extends StatelessWidget {
  const SwiperDiy({Key? key, required this.swiperDataList}) : super(key: key);

  final List<HomeBannerBean?>? swiperDataList;

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: ScreenUtil().setWidth(333).toDouble(),
      child: Swiper(
        itemCount: swiperDataList!.length,
        itemBuilder: (context, index) {
          return Image.network(
            swiperDataList![index]!.imagePath!,
            fit: BoxFit.fill,
          );
        },
        pagination: const SwiperPagination(), //设置控制轮播图的小圆点
        autoplay: true, //设置是否自动轮播
      ),
    );
  }
}

///导航控件
class HomeNavigator extends StatelessWidget {
  const HomeNavigator({Key? key, required this.navigatorList})
      : super(key: key);
  final List<HomeNavigatorBean?>? navigatorList;

  //girdViewItem的布局
  Widget _gridViewItemUI(context, HomeNavigatorBean item) {
    return InkWell(
      //无涟漪效果的图片按钮
      onTap: () {
        print('点击了导航:${item.giftname}');
      },
      child: Column(
        children: [
          SizedBox(
            child: CircleAvatar(
              backgroundImage: NetworkImage('${item.giftpath}'),
              // )
              // Image.network(
              //   '${item.giftpath}',
              //   width: ScreenUtil().setWidth(75).toDouble(),
              //   height: ScreenUtil().setHeight(75).toDouble(),
            ),
            width: ScreenUtil().setWidth(75).toDouble(),
            height: ScreenUtil().setHeight(75).toDouble(),
          ),
          Text('${item.price}')
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: ScreenUtil().setHeight(270).toDouble(),
      padding: const EdgeInsets.all(3.0),
      child: GridView.count(
        physics: const NeverScrollableScrollPhysics(),
        //屏蔽掉gridView的滚动事件,使页面可以进行整体的滚动
        crossAxisCount: 6,
        padding: const EdgeInsets.all(4.0),
        //拿到数据集合后,将它(NavigatorList)遍历并且转换(map),把其中每一个对象(e)赋值给UI的item,再形成一个集合(toList)
        //for(i in  navigatorList){  i是集合中一个个的对象bean类
        //  _gridViewItemUI(context, i))
        // childrenList .add(_gridViewItemUI(context, i)))
        //}
        children:
            navigatorList!.map((e) => _gridViewItemUI(context, e!)).toList(),
      ),
    );
  }
}

///商品推荐组件
class HomeRecommend extends StatelessWidget {
  const HomeRecommend({Key? key, required this.recommendList})
      : super(key: key);
  final List<HomeRecommendBean?>? recommendList;

  //商品推荐的标题
  Widget _titleWidget() {
    return Container(
      alignment: Alignment.centerLeft,
      padding: const EdgeInsets.fromLTRB(10, 2, 0, 5),
      decoration: const BoxDecoration(
          color: Colors.white,
          border: Border(bottom: BorderSide(width: 1, color: Colors.black12))),
      child: const Text(
        '商品推荐',
        style: TextStyle(color: Colors.pink),
      ),
    );
  }

  //商品推荐的item
  Widget _item(HomeRecommendBean item) {
    return InkWell(
      onTap: () {},
      child: Container(
        height: ScreenUtil().setHeight(300).toDouble(),
        width: ScreenUtil().setWidth(250).toDouble(),
        padding: const EdgeInsets.all(8),
        decoration: const BoxDecoration(
            color: Colors.white,
            border: Border(left: BorderSide(width: 1, color: Colors.black12))),
        child: Column(
          children: [
            Image.network(item.goods_default_icon!),
            Text(
              '团购价:￥${item.goods_default_price}元',
              style: TextStyle(fontSize: ScreenUtil().setSp(23).toDouble()),
            ),
            Text(
              '原价:￥${item.goods_default_price}元',
              style: TextStyle(
                  decoration: TextDecoration.lineThrough,
                  color: Colors.grey,
                  fontSize: ScreenUtil().setSp(19).toDouble()),
            )
          ],
        ),
      ),
    );
  }

  //横向列表组件
  Widget _recommendList() {
    return SizedBox(
      height: ScreenUtil().setHeight(330).toDouble(),
      child: ListView.builder(
          scrollDirection: Axis.horizontal,
          itemCount: recommendList!.length,
          itemBuilder: (context, index) {
            return _item(recommendList![index]!);
          }),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: ScreenUtil().setHeight(400).toDouble(),
      margin: const EdgeInsets.only(top: 10),
      child: Column(
        children: [_titleWidget(), _recommendList()],
      ),
    );
  }
}
